import axios from 'axios';
import {cookie} from './cookie';

const http = {
  checkLogin: function(props, returnUrl) {
    const sessionId = cookie.get('sid');
    if (!cookie.get('sid')) {
      const url = returnUrl || encodeURIComponent(`${props.location.pathname}${props.location.search}`);
      props.history.replace(`/login?returnUrl=${url}`);
    }
  },

  get: async function(url, params = {}) {
    return (await this.request({url, method: 'get', params})).data;
  },

  post: async function(url, data = {}, headers = {}) {
    const res = (await this.request({url, method: 'post', data, headers})).data;
    if(res.error === 1){
      window.location.href = 'http://120.132.17.103/accounts/login/';
      // 跳转登录页面
    } else {
      return res
    }
  },

  upload: async function(url, data) {
    const configs = {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    };
    return (await axios.post(url, data, configs)).data;
  },

  request: async function(config) {
    return await axios(config);
  },
};

export {
  http,
};
